import React, { createRef } from "react";
import {
  Space,
  Row,
  Table,
  Pagination,
  Typography,
  Button,
  message,
  Select,
  Form,
  Input,
  Modal
} from "antd";
import "./index.less";
import { listAdminer, createAdminer } from "@/services/adminer";
import moment from "moment";
import {
  AdminerType, getAdminerType, AdminerTenant, getAdminerTenant
} from "@/consts/consts";

// 登录的路由组件
class Adminer extends React.Component {
  // 表格
  rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      this.setState({
        rowData: selectedRows,
      });
    },
    getCheckboxProps: (record) => ({
      name: record.name
    })
  };

  constructor(props) {
    super(props);

    this.state = {
      total: 0,
      currentPage: 1,
      size: 10,
      dataSource: [],
      query: 0,
      isReady: false,
      adminerFormModalVisible: false,
      make: "",
      makeMessage: "",
      rowData: [],
      deleteFormModalVisible: false,
      deleteData: []
    };

    this.searchFormRef = createRef();
    this.AdminerFormRef = createRef();
    this.tableWrapperRef = createRef();
    this.otherHeight = 0;
  }

  // 加载table
  componentDidMount() {
    this.fetchTableData().finally(() => this.setState({ isReady: true }));
  }

  // 表格规则定义
  spawnColumns = () => [
    {
      title: "账号",
      dataIndex: "account",
      render: (value) => {
        const newValue = `${value}`;
        return (
          <p>
            {newValue.substring(0, 3)}
            ****
            {newValue.substring(7, 11)}
          </p>
        );
      }
    },
    {
      title: "昵称",
      dataIndex: "name"
    },
    {
      title: "创建日期",
      dataIndex: "time",
      render: (value) => moment.unix(value).format("YYYY-MM-DD")
    },
    {
      title: "角色类型",
      dataIndex: "type",
      render: (value) => getAdminerType(value) || "未知"
    },
    {
      title: "关联租户",
      dataIndex: "relation",
      render: (value) => getAdminerTenant(value) || "未知"
    },
    {
      title: "操作",
      dataIndex: "make",
      render: (text, record) => (
        <Space size="middle">
          <a onClick={this.editAdminer.bind(this, record)}>编辑</a>
          <a onClick={this.deleteAlert.bind(this, record)}>删除</a>
        </Space>
      )
    }
  ];

  // 页码改变时
  handlePageChange = (page, size) => {
    this.setState({ currentPage: page, size }, this.fetchTableData);
  };

  // 新建弹窗开关
  createAdminer = () => {
    this.setState({
      adminerFormModalVisible: true,
      make: "新建账号",
      makeMessage: "创建"
    });
    setTimeout(() => {
      const { setFieldsValue } = this.AdminerFormRef.current;
      setFieldsValue({
        account: null,
        name: null,
        type: null,
        relation: null
      });
    }, 100);
  };

  // 编辑弹窗开关
  editAdminer = (a) => {
    this.setState({
      adminerFormModalVisible: true,
      make: "编辑账号",
      makeMessage: "修改"
    });
    // 报错：TypeError: Cannot read property ‘setFieldsValue’ of null
    // 原因：对话框模块还没显示，也就是表单还没挂载就调用了setFieldsValue，所以报错
    // 设置定时器延迟解决
    setTimeout(() => {
      const { setFieldsValue } = this.AdminerFormRef.current;
      setFieldsValue({
        id: a.id,
        account: a.account,
        name: a.name,
        type: a.type,
        relation: a.relation
      });
    }, 100);
  };

  // 控制删除弹窗
  deleteAlert = (a) => {
    const { rowData } = this.state;
    if (a) {
      this.setState({
        deleteData: a,
        deleteFormModalVisible: true
      });
    } else if (rowData.length !== 0) {
      this.setState({
        deleteData: rowData,
        deleteFormModalVisible: true,
      });
    } else {
      message.error("未选中删除信息");
    }
  };

  // 向服务器提供删除请求
  deleteAccounts = () => {
    const { deleteData } = this.state;
    // 新建服务器函数，暂放
    createAdminer({
      data: { deleteData }
    }).then((Res) => {
      if (Res.data.ret === 0) {
        // 删除成功
        message.success("删除成功！");
        // 关闭弹窗
        this.setState({
          deleteFormModalVisible: false
        });
        this.fetchTableData();
      } else {
        // 删除失败
        message.success("删除失败");
      }
    });
  };

  // 重置对应输入框
  resetFliter = () => {
    const { resetFields } = this.searchFormRef.current;
    resetFields();
  };

  // 查询对应函数
  search = () => {
    this.fetchTableData();
  };

  // 类型选择
  AdminerTypeOptions = () => AdminerType.map((item) => (
    <Select.Option value={item.val} key={item.val}>
      {item.type}
    </Select.Option>
  ));

  // 租户选择
  AdminerTenantOptions = () => AdminerTenant.map((item) => (
    <Select.Option value={item.val} key={item.val}>
      {item.name}
    </Select.Option>
  ));

  // 获取输入框信息
  getSearchFormValue = () => {
    const { getFieldsValue } = this.searchFormRef.current;
    const { account, relation } = getFieldsValue();
    return { account, relation };
  };

  // 获取表格中部分信息,编辑功能中使用
  getAdminerFormValue = () => {
    const { getFieldsValue } = this.AdminerFormRef.current;
    const {
      account, name, type, relation, id
    } = getFieldsValue();
    return {
      account, name, type, relation, id
    };
  };

  // 新建/编辑账户发送服务端请求
  handleSaveAdminerInfo = () => {
    const {
      account, name, type, relation, id
    } = this.getAdminerFormValue();
    createAdminer({
      account,
      name,
      type,
      relation,
      id
    }).then((AdminerRes) => {
      const { makeMessage } = this.state;
      if (AdminerRes.data.ret === 0) {
        message.success(`${makeMessage}成功！`);
        this.setState({
          // 关闭新建弹窗
          adminerFormModalVisible: false
        });
      } else {
        message.error(`${makeMessage}失败`);
      }
    });
  };

  // 刷新数据
  fetchTableData = async () => {
    const { size, currentPage } = this.state;
    const { account, relation } = this.getSearchFormValue();

    const {
      data: { ret },
      data: {
        data: { list, total, query }
      }
    } = await listAdminer({
      size,
      page: currentPage,
      account,
      relation
    });

    if (ret !== 0) {
      return;
    }
    this.setState({ total, dataSource: list, query });
  };

  // 手机选择
  CustProPhoneOptions = () => (
    <Form.Item noStyle>
      <Select style={{ width: 70 }} disabled="disable" placeholder="+86" />
    </Form.Item>
  );

  // 编辑/新建弹窗样式
  renderAdminerFormModal = () => {
    const { make, adminerFormModalVisible } = this.state;
    return (
      <Modal
        centered
        title={make}
        visible={adminerFormModalVisible}
        onOk={() => this.handleSaveAdminerInfo()}
        onCancel={() => this.setState({ adminerFormModalVisible: false })}
      >
        <Form
          ref={this.AdminerFormRef}
          labelCol={{
            span: 8
          }}
          wrapperCol={{
            span: 16
          }}
        >
          <Form.Item
            name="account"
            label="账号："
            rules={[{ required: true, message: "请输入账号" }]}
          >
            <Input
              placeholder="请输入"
              style={{ width: 200 }}
              addonBefore={this.CustProPhoneOptions()}
            />
          </Form.Item>
          <Form.Item name="name" label="昵称：" rules={[{ required: true, message: "请输入昵称" }]}>
            <Input placeholder="请输入" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item
            name="type"
            label="类型："
            rules={[{ required: true, message: "请选择账号类型" }]}
          >
            <Select
              // showSearch
              placeholder="管理员"
              style={{ width: 200 }}
            >
              {this.AdminerTypeOptions()}
            </Select>
          </Form.Item>
          <Form.Item
            name="relation"
            label="相关租户："
            // rules={[{ required: true, message: '请选择账号类型' }]}
          >
            <Select
              // showSearch
              placeholder="请选择"
              style={{ width: 200 }}
            >
              {this.AdminerTenantOptions()}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  // 打开删除弹窗
  showModal = () => {
    this.setState({
      deleteFormModalVisible: true
    });
  };

  // 关闭删除弹窗
  hideModal = () => {
    this.setState({
      deleteFormModalVisible: false
    });
  };

  // 删除弹窗样式
  deleteAdminerFormModal = () => {
    const { deleteFormModalVisible } = this.state;
    return (
      <Modal
        title="重要提醒"
        visible={deleteFormModalVisible}
        onOk={this.deleteAccounts}
        onCancel={this.hideModal}
        okText="确认"
        cancelText="取消"
      >
        <p>您正在删除当前选中的内容，删除无法撤销，您确认吗？</p>
      </Modal>
    );
  };

  render() {
    const {
      total, dataSource, currentPage, size, query, isReady
    } = this.state;
    return (
      <div className="Adminer">
        <div className="AdminerSearch">
          <div className="AdminerTitle">
            <h2>
              账号管理
              <div className="blank" />
            </h2>
          </div>
          <Form ref={this.searchFormRef}>
            <Form.Item label="账号：" name="account" className="account">
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item label="关联租户：" name="relation" className="tenant">
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item className="return">
              <Button type="ghost" onClick={() => this.resetFliter()}>
                重置
              </Button>
            </Form.Item>
            <Form.Item className="search">
              <Button type="primary" onClick={() => this.search()}>
                查询
              </Button>
            </Form.Item>
          </Form>
        </div>

        <div className="AdminerList">
          <p>账号列表</p>
          <Form>
            <Form.Item className="AllDelete">
              <Button type="ghost" onClick={() => this.deleteAlert()}>
                批量删除
              </Button>
            </Form.Item>
            <Form.Item className="add">
              <Button type="primary" onClick={() => this.createAdminer()}>
                +新建
              </Button>
            </Form.Item>
          </Form>
          <Table
            rowSelection={this.rowSelection}
            pagination={false}
            loading={!isReady}
            columns={this.spawnColumns()}
            dataSource={dataSource}
          />
          <Row justify="space-between" align="middle">
            <Typography.Text>
              共
              {query}
              条记录 第
              {currentPage}
              /
              {' '}
              {Math.ceil(query / size) || 1}
              页
            </Typography.Text>

            <Pagination
              showQuickJumper
              showLessItems
              total={total}
              pageSize={10}
              current={currentPage}
              showSizeChanger={false}
              onChange={this.handlePageChange}
            />
          </Row>
        </div>
        {this.renderAdminerFormModal()}
        {this.deleteAdminerFormModal()}
      </div>
    );
  }
}

export default Adminer;
